package lin.an.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lin.an.auth.param.LoginParam;
import lin.an.auth.service.LoginService;
import lin.an.enums.StatusEnum;
import lin.an.exception.CommonException;
import lin.an.user.entity.User;
import lin.an.user.mapper.UserMapper;
import lin.an.util.CommonCryptogramUtil;
import org.springframework.stereotype.Service;

/**
 * @author zhoulinq
 * @date 2025/4/1
 */
@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {
    @Override
    public String doLogin(LoginParam loginParam) {
        if(loginParam.getAccount() == null || loginParam.getPassword() == null){
            throw new CommonException("账号或者密码不能为空");
        }
        //加密密码
        loginParam.setPassword(CommonCryptogramUtil.doSm4Encrypt(loginParam.getPassword()));
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getAccount,loginParam.getAccount())
                .eq(User::getPassword,loginParam.getPassword());
        User user = this.getOne(lambdaQueryWrapper);
        if(ObjectUtil.isEmpty(user)){
            throw new CommonException("用户名或者密码错误");
        } else {
            // 检查用户状态
            if(user.getStatus().equals(StatusEnum.DISABLED.getValue())) {
                throw new CommonException("您的账号已被封禁，涉嫌违规操作，如有需要请联系管理员邮箱1376663122@qq.com");
            }
            StpUtil.login(user.getUserId());
            return StpUtil.getTokenInfo().tokenValue;
        }
    }
}
